package com.example.mvvm.base;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;

import com.example.mvvm.BR;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseAdapter<T, VDB extends ViewDataBinding> extends RecyclerView.Adapter<BaseViewHolder<VDB>> {

    private List<T> data=new ArrayList<>();
    private final int layoutId;
    private SparseArray<BaseViewHolder<VDB>> holders = new SparseArray<>();

    public BaseAdapter(List<T> data, int layoutId) {
        this.data = data;
        this.layoutId = layoutId;
    }

    public void setData(List<T> data) {
        int oldSize = this.data.size();
        this.data.addAll(data);
        notifyItemRangeChanged(oldSize, this.data.size());
    }

    public T getData(int position) {
        if (data.isEmpty()) {
            return null;
        }
        return data.get(position);
    }

    @NonNull
    @Override
    public BaseViewHolder<VDB> onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);
        BaseViewHolder<VDB> viewHolder = new BaseViewHolder<>(DataBindingUtil.inflate(inflater, layoutId, parent, false));
        onCreateViewHolder(viewHolder);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull BaseViewHolder<VDB> holder, int position) {
        VDB binding = DataBindingUtil.getBinding(holder.itemView);
        binding.setVariable(BR.data, data.get(position));
        binding.executePendingBindings();
        holders.put(position, holder);
        this.onBind(holder, position, data.get(position), binding);
    }

    @Override
    public int getItemCount() {
        return data == null ? 0 : data.size();
    }

    protected abstract void onCreateViewHolder(BaseViewHolder<VDB> viewHolder);

    protected void onBind(@NonNull BaseViewHolder<VDB> holder, int position, T t, VDB binding) {

    }
    public BaseViewHolder<VDB> getHolders(int position) {
        if (holders.size() == 0) {
            return null;
        }
        return holders.get(position);
    }
}
